package userManage

import (
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"main/src/utils"
)

type User struct {
	gorm.Model
	Id       int    `gorm:"type:int(11);primaryKey;autoIncrement"`
	Username string `gorm:"type:varchar(32);not null;unique;uniqueIndex "` //用户名
	Password string `gorm:"type:varchar(256);not null"`                    // 密码
	IsSuper  bool   `gorm:"type:bool;not null;default:false"`              //是否超级管理员
	IsBackUp bool   `gorm:"type:bool;not null;default true"`               //是否停用
}

func (u *User) Export(userJwtInfo *utils.UserJWTInfo) {
	userJwtInfo.Id = u.Id
	userJwtInfo.Username = u.Username
	userJwtInfo.Password = u.Password
	userJwtInfo.IsSuper = u.IsSuper
	userJwtInfo.IsBackUp = u.IsBackUp
	userJwtInfo.UpdatedAt = u.UpdatedAt
	userJwtInfo.CreatedAt = u.CreatedAt
}

// SetPassword 密码加密存储
func (u *User) SetPassword(password string) {
	hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) //加密处理
	println(password)
	println(hash)
	u.Password = string(hash)
}

// CheckedPassword 密码校验
func (u *User) CheckedPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err == nil {
		return true
	} else {
		return false
	}
}

func (u *User) TableName() string {
	return "user"
}
